package com.atguigu_g_semphore;

import java.util.concurrent.Semaphore;

public class Demo {
    public static void main(String[] args) {
        //创建Semphore对象
        Semaphore semaphore = new Semaphore(2); //代表2个通行证

        for (int i = 1; i <= 1000; i++) {
            //创建1千个线程对象并启动
            new MyThread("车辆 " + i,semaphore).start();
        }
    }
}


//线程类
class MyThread extends Thread{
    //属性 : 获取Semphore对象
    private Semaphore semaphore;

    //生成构造方法
    public MyThread(String name, Semaphore semaphore) {
        super(name);
        this.semaphore = semaphore;
    }

    //重写线程的任务
    @Override
    public void run() {
        try {
            //先获取通行证
            semaphore.acquire();
            System.out.println(getName() + " 获取了通行证 !");

            System.out.println(getName() + " 正在通过路口 !");
            Thread.sleep(1000);

            //再释放通行证
            System.out.println(getName() + " 释放了通行证 !");

            semaphore.release();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }


    }
}